<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage,ElMessageBox} from 'element-plus'
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { roleListService,addRoleService,updateRoleService,deleteRoleService } from "@/api/role"



//分页条数据模型
const page = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数
//用户角色数据模型
const role = ref([
    {
    "id": 1,
    "roleName": "管理员",
    "roleKey" : "ADMIN",
    "status" : 1,
    }
]) as any;
const roleList = async () => {
    let params = {
        page: page.value,
        pageSize: pageSize.value,
    }
    let result = await roleListService(params)

    //渲染视图
    total.value = result.data.total;
    role.value = result.data.records;
}
//调用函数查询
roleList();
//当每页条数发生了变化，调用此函数
const handleSizeChange = (size: number) => {
    pageSize.value = size
    roleList();
}
//当前页码发生变化，调用此函数
const handleCurrentChange = (num: number) => {
    page.value = num
    roleList();
}
//添加角色表单模型
const roleForm = ref({
    id: 1,
    roleName: '',
    roleKey: '',
    status: 1,
})
//添加角色的表单校验模型
const Rules = ref({
    roleName: [
        { required: true, message: '请输入角色名', trigger: 'blur' }
    ],
    roleKey: [
        { required: true, message: '请输入角色关键字', trigger: 'blur' }
    ]
})
//默认不显示抽屉
const visibleDrawer = ref(false)
//为抽屉添加响应数据
const addRoleRef = ref()
//后台调用添加角色接口
const onAdd = async () => {
    //点击添加按钮后再进行二次校验
    await addRoleRef.value?.validate().catch((err: any) => { ElMessage.error("校验失败"); return Promise.reject(err) })
    let result = await addRoleService(roleForm.value) as any;
    ElMessage.success(result.msg ? result.msg : '添加成功')
    //让抽屉消失
    visibleDrawer.value = false
    //刷新列表
    roleList();
}
//刷新抽屉表单
const clearRoleForm = () => {
    roleForm.value = {
        id : 1 ,
        roleName: '',
        roleKey: '',
        status : 1
    }
}
//取消添加
const cancelDrawer = () => {
    visibleDrawer.value = false
}

//默认不显示对话框
const visibleDialog = ref(false)
//展示编辑对话框弹窗
const showDialog = (row: { roleName: string; roleKey: string; status: number; id: number }) => {
    clearRoleForm()
    visibleDialog.value = true
    //给编辑框回写原先信息
    roleForm.value.roleName = row.roleName
    roleForm.value.roleKey = row.roleKey
    roleForm.value.status = row.status
    //扩展模型添加id
    roleForm.value.id = row.id
}

//为对话框添加响应数据
const updateUserRef = ref()
//后台调用修改角色接口
const updateRole =async () =>{
    //点击修改后再进行二次校验
    await updateUserRef.value?.validate().catch((err: any) => { ElMessage.error("校验失败"); return Promise.reject(err) })
    let result = await updateRoleService(roleForm.value) as any;
    ElMessage.success(result.msg ? result.msg : '修改成功')
    //让对话框消失
    visibleDialog.value = false
    //刷新列表
    roleList();
}
//取消修改
const cancelDialog = () => {
    visibleDialog.value = false
}
//删除角色
const deleteRole = (row: { id: any }) => {
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result = await deleteRoleService(row.id) as any;
            ElMessage({
                type: 'success',
                message: result.msg ? result.msg : '删除成功',
            })
            roleList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
//点击修改权限路由跳转并携带当前角色id参数
const router = useRouter();
const updatePermission = (row: any) =>{
    router.push({
        path:"/admin/permission",
        query:{
                id: row.id
        }
    }) 
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>角色管理</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer = true; clearRoleForm()">添加角色</el-button>
                </div>
            </div>
        </template>
        <!-- 角色列表 -->
        <el-table :data="role" style="width: 100%">
            <el-table-column label="序号" width="100">
                <template v-slot="scope">
                    <!-- 序号实现自动增加且连续 -->
                    {{ (page - 1) * pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column prop="roleName" label="角色名"  width="200"></el-table-column>
            <el-table-column prop="roleKey" label="角色关键字"   width="120"></el-table-column>
            <el-table-column prop="status" label="角色状态"  show-overflow-tooltip width="120">
                <!-- 将渲染的1，0转换为正常，禁用 -->
                <template v-slot="scope">{{ scope.row.status === 1 ? '正常' : '禁用' }}</template>
            </el-table-column>
            <el-table-column label="操作" width="300">
                <template #default="{ row }">
                    <el-button :icon="Edit"  plain type="primary" @click="showDialog(row)" >编辑</el-button>
                    <el-button :icon="Delete"  plain type="danger" @click="deleteRole(row)">删除</el-button>
                    <el-button  link plain type="primary" @click="updatePermission(row)" >查看权限</el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" background
            layout="sizes,prev, pager,next,jumper,total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :total="total">
        </el-pagination>

        <!-- 抽屉中嵌套添加表单 -->
        <el-drawer v-model="visibleDrawer" title="添加角色" direction="rtl" destroy-on-close>
            <div>
                <el-form ref="addRoleRef" :model="roleForm" :rules="Rules">
                    <el-form-item label="角色名" prop="roleName">
                        <el-input v-model="roleForm.roleName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="角色关键字" prop="roleKey">
                        <el-input v-model="roleForm.roleKey" autocomplete="off" />
                    </el-form-item>
                </el-form>
                <!-- 按钮设置 -->
                <div>
                    <el-button @click="cancelDrawer(); clearRoleForm()">取消</el-button>
                    <el-button type="primary" @click="onAdd">
                        添加
                    </el-button>
                </div>
            </div>
        </el-drawer>

        <!-- 对话框嵌套编辑表单 -->
        <el-dialog v-model="visibleDialog" title="修改角色" destroy-on-close>
            <div>
                <el-form ref="updateRoleRef" :model="roleForm" :rules="Rules">
                    <el-form-item label="角色名" prop="roleName">
                        <el-input v-model="roleForm.roleName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="角色关键字" prop="roleKey">
                        <el-input v-model="roleForm.roleKey" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="角色状态" prop="status">
                        <el-select placeholder="请选择" v-model="roleForm.status">
                            <el-option label="正常" :value="1" />
                            <el-option label="禁用" :value="0" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <!-- 按钮设置 -->
                <div>
                    <el-button @click="cancelDialog(); clearRoleForm()">取消</el-button>
                    <el-button type="primary" @click="updateRole">
                        修改
                    </el-button>
                </div>
            </div>
        </el-dialog>
    </el-card>
</template>


<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>